import React, { useState, useEffect } from 'react';
import {
  AppBar,
  Toolbar,
  Typography,
  Container,
  Card,
  CardContent,
  CardMedia,
  Grid,
  Button,
  Dialog,
  DialogContent,
  DialogActions,
  FormControl,
  InputLabel,
  Select,
  MenuItem,
  Pagination,
  Box,
  Alert,
  CircularProgress,
  IconButton,
  Chip
} from '@mui/material';
import {
  Download,
  Print,
  Delete,
  Close,
  QrCode2,
  Refresh,
  Sort,
  AccessTime,
  SortByAlpha
} from '@mui/icons-material';
import { createTheme, ThemeProvider, useTheme } from '@mui/material/styles';
import { useMediaQuery } from '@mui/material';
import CssBaseline from '@mui/material/CssBaseline';
import { BrowserRouter as Router, Routes, Route } from 'react-router-dom';
import { api, ImageFile, Folder, PaginationInfo } from './request';
import AdminApp from './admin/AdminApp';

const theme = createTheme({
  palette: {
    mode: 'light',
    primary: {
      main: '#2196f3',
    },
    secondary: {
      main: '#f44336',
    },
  },
});

// 接口定义已移至 request.ts 文件

function MainApp() {
  const theme = useTheme();
  const isMobile = useMediaQuery(theme.breakpoints.down('md'));
  
  const [folders, setFolders] = useState<Folder[]>([]);
  const [selectedFolder, setSelectedFolder] = useState<string>('');
  const [images, setImages] = useState<ImageFile[]>([]);
  const [currentPage, setCurrentPage] = useState(1);
  const [pagination, setPagination] = useState<PaginationInfo>({ page: 1, per_page: 20, total: 0, pages: 1 });
  const [loading, setLoading] = useState(false);
  const [status, setStatus] = useState<{ message: string; type: 'success' | 'error' | 'info' }>({ message: '正在初始化...', type: 'info' });
  const [selectedImage, setSelectedImage] = useState<ImageFile | null>(null);
  const [dialogOpen, setDialogOpen] = useState(false);
  const [sortBy, setSortBy] = useState<'time' | 'name'>('time');
  const [sortOrder, setSortOrder] = useState<'asc' | 'desc'>('desc');
  const [backgroundConfig, setBackgroundConfig] = useState<{ headerBg?: string; pageBg?: string }>({});

  // 自动登录和加载背景配置
  useEffect(() => {
    autoLogin();
    loadBackgroundConfig();
  }, []);

  const loadBackgroundConfig = async () => {
    try {
      const response = await api.getBackgroundConfig();
      if (response.success && response.data) {
        const configs = response.data;
        const newConfig: { headerBg?: string; pageBg?: string } = {};
        
        configs.forEach((config: any) => {
          if (config.is_active) {
            if (config.config_type === 'header') {
              newConfig.headerBg = config.image_url;
            } else if (config.config_type === 'background') {
              newConfig.pageBg = config.image_url;
            }
          }
        });
        
        setBackgroundConfig(newConfig);
      }
    } catch (error) {
      console.log('加载背景配置失败:', error);
    }
  };

  const autoLogin = async () => {
    setStatus({ message: '正在自动登录...', type: 'info' });
    try {
      const data = await api.login();
      
      if (data.success) {
        setStatus({ message: '登录成功，正在加载文件夹...', type: 'success' });
        loadFolders();
      } else {
        setStatus({ message: `自动登录失败: ${data.message}`, type: 'error' });
      }
    } catch (error) {
      setStatus({ message: `登录请求失败: ${error}`, type: 'error' });
    }
  };

  const loadFolders = async () => {
    try {
      const data = await api.getFolders();
      
      if (data.success) {
        setFolders(data.folders);
        setStatus({ message: `找到 ${data.count} 个文件夹`, type: 'success' });
        
        if (data.folders.length > 0) {
          const firstFolder = data.folders[0];
          setSelectedFolder(firstFolder.path);
          loadImages(firstFolder.path, 1);
        }
      } else {
        setStatus({ message: `加载文件夹失败: ${data.message}`, type: 'error' });
      }
    } catch (error) {
      setStatus({ message: `请求失败: ${error}`, type: 'error' });
    }
  };

  const loadImages = async (folderPath: string, page: number = 1, currentSortBy?: 'time' | 'name', currentSortOrder?: 'asc' | 'desc') => {
    if (!folderPath) return;
    
    setLoading(true);
    setStatus({ message: '正在加载图片...', type: 'info' });
    
    const sortByParam = currentSortBy || sortBy;
    const sortOrderParam = currentSortOrder || sortOrder;
    
    try {
      const data = await api.getImages(folderPath, page, 20, sortByParam, sortOrderParam);
      
      if (data.success) {
        setImages(data.images);
        setPagination(data.pagination);
        setCurrentPage(page);
        setStatus({ message: `加载了 ${data.images.length} 张图片`, type: 'success' });
      } else {
        setStatus({ message: `加载图片失败: ${data.message}`, type: 'error' });
      }
    } catch (error) {
      setStatus({ message: `请求失败: ${error}`, type: 'error' });
    } finally {
      setLoading(false);
    }
  };

  const handleFolderChange = (folderPath: string) => {
    setSelectedFolder(folderPath);
    loadImages(folderPath, 1);
  };

  const handlePageChange = (event: React.ChangeEvent<unknown>, page: number) => {
    loadImages(selectedFolder, page);
  };

  const handleImageClick = (image: ImageFile) => {
    setSelectedImage(image);
    setDialogOpen(true);
  };

  const handleDownload = (imagePath: string) => {
    const downloadUrl = api.getDownloadUrl(imagePath);
    window.open(downloadUrl, '_blank');
  };

  const handlePrint = (imagePath: string, imageName: string) => {
    const largeImageUrl = api.getThumbnailUrl(imagePath, 'large');
    const printWindow = window.open('', '_blank');
    if (printWindow) {
      printWindow.document.write(`
        <html>
          <head>
            <title>打印 - ${imageName}</title>
            <style>
              body { margin: 0; padding: 20px; text-align: center; }
              img { max-width: 100%; max-height: 90vh; object-fit: contain; }
              h3 { margin-bottom: 20px; }
              @media print {
                body { padding: 0; }
                h3 { display: none; }
              }
            </style>
          </head>
          <body>
            <h3>${imageName}</h3>
            <img src="${largeImageUrl}" alt="${imageName}" onload="window.print(); window.close();" />
          </body>
        </html>
      `);
      printWindow.document.close();
    }
  };

  const handleDelete = async (imagePath: string, imageName: string) => {
    if (!window.confirm(`确定要删除图片 "${imageName}" 吗？\n\n此操作不可撤销！`)) {
      return;
    }
    
    try {
      const data = await api.deleteImage(imagePath);
      
      if (data.success) {
        alert('文件删除成功！');
        setDialogOpen(false);
        loadImages(selectedFolder, currentPage);
      } else {
        alert(`删除失败: ${data.message}`);
      }
    } catch (error) {
      alert(`删除请求失败: ${error}`);
    }
  };

  const getQRCodeUrl = (imagePath: string) => {
    return api.getQRCodeUrl(imagePath, 200);
  };

  const handleRefresh = () => {
    if (selectedFolder) {
      loadImages(selectedFolder, currentPage);
    }
  };

  const handleSortChange = (newSortBy: 'time' | 'name') => {
    if (newSortBy === sortBy) {
      // 如果点击相同的排序方式，切换升序/降序
      const newSortOrder = sortOrder === 'desc' ? 'asc' : 'desc';
      setSortOrder(newSortOrder);
      loadImages(selectedFolder, 1, sortBy, newSortOrder);
    } else {
      // 如果点击不同的排序方式，使用默认排序
      const defaultOrder = newSortBy === 'time' ? 'desc' : 'asc';
      setSortBy(newSortBy);
      setSortOrder(defaultOrder);
      loadImages(selectedFolder, 1, newSortBy, defaultOrder);
    }
  };

  return (
    <ThemeProvider theme={theme}>
      <CssBaseline />
      <Box
        sx={{
          minHeight: '100vh',
          backgroundImage: backgroundConfig.pageBg ? `url(${backgroundConfig.pageBg})` : 'none',
          backgroundSize: 'cover',
          backgroundPosition: 'center',
          backgroundAttachment: 'fixed'
        }}
      >
        <AppBar 
          position="sticky"
          sx={{
            backgroundImage: backgroundConfig.headerBg ? `url(${backgroundConfig.headerBg})` : 'none',
            backgroundSize: 'cover',
            backgroundPosition: 'center'
          }}
        >
          <Toolbar sx={{ minHeight: 64, height: 80 }}>
            <Typography variant="h6" component="div" sx={{ flexGrow: 1 }}>
            </Typography>
          </Toolbar>
        </AppBar>
        
        <Container maxWidth="lg" sx={{ pt: 3, pb: 3 }}>
        <Alert severity={status.type} sx={{ mb: 3 }}>
          {status.message}
        </Alert>
        
        {folders.length > 0 && (
          <Card sx={{ mb: 3 }}>
            <CardContent>
              <FormControl fullWidth>
                <InputLabel>选择文件夹</InputLabel>
                <Select
                  value={selectedFolder}
                  label="选择文件夹"
                  onChange={(e) => handleFolderChange(e.target.value)}
                >
                  {folders.map((folder) => (
                    <MenuItem key={folder.path} value={folder.path}>
                      {folder.name}
                    </MenuItem>
                  ))}
                </Select>
              </FormControl>
              <Box sx={{ mt: 2, display: 'flex', alignItems: 'center', gap: 1, flexWrap: 'wrap' }}>
                {pagination.total > 0 && (
                  <Chip 
                    label={`${pagination.total} 张图片`} 
                    color="primary" 
                  />
                )}
                {selectedFolder && (
                  <>
                    <IconButton 
                      onClick={handleRefresh}
                      color="primary"
                      size="small"
                      title="刷新图片列表"
                      disabled={loading}
                    >
                      <Refresh />
                    </IconButton>
                    <Box sx={{ display: 'flex', alignItems: 'center', gap: 0.5 }}>
                      <IconButton 
                        onClick={() => handleSortChange('time')}
                        color={sortBy === 'time' ? 'primary' : 'default'}
                        size="small"
                        title={`按时间排序 (${sortBy === 'time' ? (sortOrder === 'desc' ? '最新在前' : '最旧在前') : '点击切换'})`}
                        disabled={loading}
                        sx={{
                          backgroundColor: sortBy === 'time' ? 'primary.main' : 'transparent',
                          color: sortBy === 'time' ? 'white' : 'inherit',
                          '&:hover': {
                            backgroundColor: sortBy === 'time' ? 'primary.dark' : 'rgba(0, 0, 0, 0.04)'
                          }
                        }}
                      >
                        <AccessTime fontSize="small" />
                      </IconButton>
                      <IconButton 
                        onClick={() => handleSortChange('name')}
                        color={sortBy === 'name' ? 'primary' : 'default'}
                        size="small"
                        title={`按名称排序 (${sortBy === 'name' ? (sortOrder === 'desc' ? 'Z-A' : 'A-Z') : '点击切换'})`}
                        disabled={loading}
                        sx={{
                          backgroundColor: sortBy === 'name' ? 'primary.main' : 'transparent',
                          color: sortBy === 'name' ? 'white' : 'inherit',
                          '&:hover': {
                            backgroundColor: sortBy === 'name' ? 'primary.dark' : 'rgba(0, 0, 0, 0.04)'
                          }
                        }}
                      >
                        <SortByAlpha fontSize="small" />
                      </IconButton>
                    </Box>
                  </>
                )}
              </Box>
            </CardContent>
          </Card>
        )}
        
        {loading ? (
          <Box display="flex" justifyContent="center" alignItems="center" minHeight="200px">
            <CircularProgress />
            <Typography variant="body1" sx={{ ml: 2 }}>正在加载图片...</Typography>
          </Box>
        ) : images.length === 0 ? (
          <Box textAlign="center" py={8}>
            <Typography variant="h4" color="textSecondary">📷</Typography>
            <Typography variant="body1" color="textSecondary">该文件夹中没有找到图片文件</Typography>
          </Box>
        ) : (
          <>
            <Box sx={{ 
               display: 'grid', 
               gridTemplateColumns: 'repeat(auto-fill, minmax(200px, 1fr))', 
               gap: 2 
             }}>
               {images.map((image) => (
                 <Card 
                   key={image.path}
                   sx={{ 
                     cursor: 'pointer',
                     transition: 'all 0.2s ease',
                     '&:hover': {
                       transform: 'translateY(-4px)',
                       boxShadow: 4
                     }
                   }}
                   onClick={() => handleImageClick(image)}
                 >
                   <CardMedia
                     component="img"
                     height="160"
                     image={api.getThumbnailUrl(image.path, 'small')}
                     alt={image.name}
                     sx={{ objectFit: 'cover' }}
                   />
                   <CardContent sx={{ p: 2 }}>
                     <Typography 
                       variant="body2" 
                       fontWeight="bold" 
                       noWrap 
                       title={image.name}
                     >
                       {image.name}
                     </Typography>
                     <Typography variant="caption" color="textSecondary" display="block">
                       {image.size} • {image.mtime}
                     </Typography>
                   </CardContent>
                 </Card>
               ))}
             </Box>
            
            {pagination.pages > 1 && (
              <Box display="flex" justifyContent="center" mt={4}>
                <Pagination 
                  count={pagination.pages} 
                  page={currentPage} 
                  onChange={handlePageChange}
                  color="primary"
                  size="large"
                />
              </Box>
            )}
          </>
        )}
        </Container>
      </Box>
      
      {/* 图片详情对话框 */}
      <Dialog 
        open={dialogOpen} 
        onClose={() => setDialogOpen(false)}
        maxWidth={isMobile ? false : "lg"}
        fullWidth
        fullScreen={isMobile}
      >
        {selectedImage && (
          <>
            <DialogContent sx={{ 
              p: 0, 
              display: 'flex', 
              flexDirection: isMobile ? 'column' : 'row',
              minHeight: isMobile ? '100vh' : '500px',
              height: isMobile ? '100vh' : 'auto'
            }}>
              <Box sx={{ 
                flex: isMobile ? 'none' : 2, 
                display: 'flex', 
                alignItems: 'center', 
                justifyContent: 'center', 
                bgcolor: '#f5f5f5',
                height: isMobile ? '60vh' : 'auto',
                position: 'relative'
              }}>
                <img 
                  src={api.getThumbnailUrl(selectedImage.path, 'large')}
                  alt={selectedImage.name}
                  style={{ 
                    maxWidth: '100%', 
                    maxHeight: isMobile ? '60vh' : '80vh', 
                    objectFit: 'contain',
                    width: isMobile ? '100%' : 'auto'
                  }}
                />
                {isMobile && (
                  <IconButton 
                    onClick={() => setDialogOpen(false)}
                    sx={{ 
                      position: 'absolute', 
                      top: 8, 
                      right: 8,
                      bgcolor: 'rgba(0,0,0,0.5)',
                      color: 'white',
                      '&:hover': {
                        bgcolor: 'rgba(0,0,0,0.7)'
                      }
                    }}
                  >
                    <Close />
                  </IconButton>
                )}
              </Box>
              <Box sx={{ 
                flex: isMobile ? 'none' : 1, 
                p: isMobile ? 2 : 3, 
                minWidth: isMobile ? 'auto' : '300px', 
                display: 'flex', 
                flexDirection: 'column',
                height: isMobile ? '40vh' : 'auto',
                overflow: isMobile ? 'auto' : 'visible'
              }}>
                {!isMobile && (
                  <IconButton 
                    onClick={() => setDialogOpen(false)}
                    sx={{ position: 'absolute', top: 8, right: 8 }}
                  >
                    <Close />
                  </IconButton>
                )}
                
                <Typography variant="h6" gutterBottom sx={{ mt: 2, wordBreak: 'break-all' }}>
                  {selectedImage.name}
                </Typography>
                
                <Typography variant="body2" color="textSecondary" gutterBottom>
                  大小: {selectedImage.size}
                </Typography>
                
                <Typography variant="body2" color="textSecondary" gutterBottom>
                  修改时间: {selectedImage.mtime}
                </Typography>
                
                <Box sx={{ 
                  flex: 1, 
                  display: 'flex', 
                  flexDirection: 'column', 
                  justifyContent: isMobile ? 'flex-start' : 'center', 
                  alignItems: 'center', 
                  mt: isMobile ? 1 : 3 
                }}>
                  <Typography variant={isMobile ? "body1" : "subtitle1"} gutterBottom>
                    扫码下载
                  </Typography>
                  
                  <img 
                    src={getQRCodeUrl(selectedImage.path)}
                    alt="下载二维码"
                    style={{ 
                      width: isMobile ? 150 : 200, 
                      height: isMobile ? 150 : 200, 
                      border: '1px solid #e0e0e0', 
                      borderRadius: 8 
                    }}
                  />
                  
                  <Box sx={{ 
                    mt: isMobile ? 1 : 2, 
                    display: 'flex', 
                    flexDirection: 'column', 
                    gap: isMobile ? 0.5 : 1, 
                    width: '100%' 
                  }}>
                    <Button 
                      variant="contained" 
                      startIcon={<Download />}
                      onClick={() => handleDownload(selectedImage.path)}
                      fullWidth
                    >
                      下载
                    </Button>
                    
                    <Button 
                      variant="outlined" 
                      startIcon={<Print />}
                      onClick={() => handlePrint(selectedImage.path, selectedImage.name)}
                      fullWidth
                    >
                      打印
                    </Button>
                    
                    <Button 
                      variant="outlined" 
                      color="error"
                      startIcon={<Delete />}
                      onClick={() => handleDelete(selectedImage.path, selectedImage.name)}
                      fullWidth
                    >
                      删除
                    </Button>
                  </Box>
                </Box>
              </Box>
            </DialogContent>
          </>
        )}
      </Dialog>
    </ThemeProvider>
  );
}

function App() {
  return (
    <Router>
      <Routes>
        <Route path="/admin/*" element={<AdminApp />} />
        <Route path="/*" element={<MainApp />} />
      </Routes>
    </Router>
  );
}

export default App;
